/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.anny.prodcuct.web;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.beans.ResultBean;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.anny.prodcuct.entity.CategoryResponseBody;
import com.jeeplus.modules.anny.prodcuct.entity.ProductCategory;
import com.jeeplus.modules.anny.prodcuct.entity.ProductCommodity;
import com.jeeplus.modules.anny.prodcuct.service.ProductCategoryService;
import com.jeeplus.modules.anny.prodcuct.service.ProductCommodityService;

/**
 * 应用于商品分类的类别表Controller
 * @author zhengcq
 * @version 2018-10-17
 */
@Controller
@RequestMapping(value = "${adminPath}/anny/prodcuct/productCategory")
public class ProductCategoryController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ProductCategoryController.class);

	@Autowired
	private ProductCategoryService productCategoryService;
	@Autowired
	private ProductCommodityService productCommodityService;
	
	@ModelAttribute
	public ProductCategory get(@RequestParam(required=false) String id) {
		ProductCategory entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = productCategoryService.get(id);
		}
		if (entity == null){
			entity = new ProductCategory();
		}
		return entity;
	}
	
	/**
	 * 类别列表页面
	 */
	@RequiresPermissions("anny:prodcuct:productCategory:list")
	@RequestMapping(value = {"list", ""})
	public String list(ProductCategory productCategory, Model model) {
		model.addAttribute("productCategory", productCategory);
		return "modules/anny/prodcuct/productCategoryList";
	}



	
		/**
	 * 类别列表数据
	 */
	@ResponseBody
	@RequiresPermissions("anny:prodcuct:productCategory:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ProductCategory productCategory, HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			request.setCharacterEncoding("utf-8");
			productCategory.setName(new String(request.getParameter("name").getBytes("iso8859-1"),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Page<ProductCategory> page = productCategoryService.findPage(new Page<ProductCategory>(request, response), productCategory); 
		return getBootstrapData(page);
	}

	/**
	 * 类别列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "categoryData")
	public ResultBean<List<CategoryResponseBody>> categoryData(ProductCategory productCategory) {
		ResultBean<List<CategoryResponseBody>> resultBean =  new ResultBean<>();
        logger.info("++++++++查询类别表开始++++++++");
        try {
            List<CategoryResponseBody> list = productCategoryService.getCategory(productCategory);
            resultBean.setData(list);
            if (list != null && list.size() > 0){
                resultBean.setMsg("获取数据成功");
            }else {
                resultBean.setMsg("库中暂无数据");
            }
        } catch (Exception e) {
            resultBean.setCode(ResultBean.UNKNOWN_EXCEPTION);
            logger.info("++++++++"+e.getMessage()+"++++++++");
        }
        logger.info("++++++++查询类别表结束++++++++");
        return resultBean;
	}

	/**
	 * 通过父类类别编码获取列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "categorySonData")
	public ResultBean<List<ProductCategory>> categorySonData(ProductCategory productCategory) {
		ResultBean<List<ProductCategory>> resultBean =  new ResultBean<>();
		logger.info("++++++++通过父类类别编码获取列表数据开始++++++++");
		try {
			List<ProductCategory> list = productCategoryService.findList(productCategory);
			resultBean.setData(list);
			if (list != null && list.size() > 0){
				resultBean.setMsg("获取数据成功");
			}else {
				resultBean.setMsg("库中暂无数据");
			}
		} catch (Exception e) {
			resultBean.setCode(ResultBean.UNKNOWN_EXCEPTION);
			logger.info("++++++++"+e.getMessage()+"++++++++");
		}
		logger.info("++++++++通过父类类别编码获取列表数据结束++++++++");
		return resultBean;
	}

	/**
	 * 查看，增加，编辑类别表单页面
	 */
	@RequiresPermissions(value={"anny:prodcuct:productCategory:view","anny:prodcuct:productCategory:add","anny:prodcuct:productCategory:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(ProductCategory productCategory, Model model) {
		model.addAttribute("productCategory", productCategory);
		if(StringUtils.isBlank(productCategory.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/anny/prodcuct/productCategoryForm";
	}

	/**
	 * 保存类别
	 */
	@RequiresPermissions(value={"anny:prodcuct:productCategory:add","anny:prodcuct:productCategory:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(ProductCategory productCategory, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, productCategory)){
			return form(productCategory, model);
		}
		//新增或编辑表单保存
		productCategoryService.save(productCategory);//保存
		addMessage(redirectAttributes, "保存类别成功");
		return "redirect:"+Global.getAdminPath()+"/anny/prodcuct/productCategory/list";
	}
	
	/**
	 * 删除类别
	 */
	@ResponseBody
	@RequiresPermissions("anny:prodcuct:productCategory:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ProductCategory productCategory, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		productCategoryService.delete(productCategory);
		j.setMsg("删除类别成功");
		return j;
	}
	
	/**
	 * 批量删除类别
	 */
	@ResponseBody
	@RequiresPermissions("anny:prodcuct:productCategory:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			//逻辑删除需判断是否存在商品
			List<ProductCommodity> list = productCommodityService.findListByCategoryId(id);
			if(list != null && list.size() > 0){
				j.setMsg("该类别下存在商品，无法删除");
				continue;
			}else{
				j.setMsg("删除类别成功");
			}
			productCategoryService.delete(productCategoryService.get(id));
		}
//		j.setMsg("删除类别成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("anny:prodcuct:productCategory:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(ProductCategory productCategory, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "类别"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ProductCategory> page = productCategoryService.findPage(new Page<ProductCategory>(request, response, -1), productCategory);
    		new ExportExcel("类别", ProductCategory.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出类别记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("anny:prodcuct:productCategory:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ProductCategory> list = ei.getDataList(ProductCategory.class);
			for (ProductCategory productCategory : list){
				try{
					productCategoryService.save(productCategory);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条类别记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条类别记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入类别失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/anny/prodcuct/productCategory/?repage";
    }
	
	/**
	 * 下载导入类别数据模板
	 */
	@RequiresPermissions("anny:prodcuct:productCategory:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "类别数据导入模板.xlsx";
    		List<ProductCategory> list = Lists.newArrayList(); 
    		new ExportExcel("类别数据", ProductCategory.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/anny/prodcuct/productCategory/?repage";
    }

}